package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.ProductBunchDao;
import com.lei.springbootpractice.pojo.ProductBunchPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductBunchService {
    @Autowired
    ProductBunchDao productBunchDao;

    public List<ProductBunchPojo> getByCartId(String cartId) {
        return productBunchDao.selectList(new QueryWrapper<ProductBunchPojo>()
            .eq("cart_id", cartId)
            .eq("status", "IN_CART"));
    }

    public List<ProductBunchPojo> getByUserId(String userId) {
        return productBunchDao.selectList(new QueryWrapper<ProductBunchPojo>().eq("user_id", userId));
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateProductBunch(ProductBunchPojo productBunch) {

        // 执行更新
        int result = productBunchDao.updateById(productBunch);
        if (result <= 0) {
            throw new RuntimeException("更新ProductBunch失败");
        }

        // 验证更新结果
        ProductBunchPojo updated = productBunchDao.selectById(productBunch.getProductBunchID());
        if (updated == null) {
            throw new RuntimeException("更新后无法查询到ProductBunch");
        }
        return true;
    }

    public List<ProductBunchPojo> getByOrderId(String orderId) {
        return productBunchDao.selectList(new QueryWrapper<ProductBunchPojo>().eq("order_id", orderId));
    }

    public ProductBunchPojo getProductBunchById(String productBunchID) {
        return productBunchDao.selectById(productBunchID);
    }
}
